<!-- YourComponent.vue -->
<template>
    <div style="justify-items: center;">
        <el-autocomplete v-model="state" :fetch-suggestions="querySearch" popper-class="my-autocomplete"
            placeholder="请输入" @select="handleSelect" style="max-width: 500px;">
            <template #suffix>

            </template>
            <template #default="{ item }">
                <div class="value">{{ item.title }}</div>
                <span class="link">{{ item.url }}</span>
            </template>
        </el-autocomplete>
        <el-button type="primary" @click="handleButtonClick">Search</el-button>
    </div>
</template>

<script setup>

import axios from 'axios';
import { useRouter } from 'vue-router';
import { ref, onMounted } from 'vue';

const router = useRouter();
const state = ref('');
const selectedId = ref(null);
const links = ref([]);

const querySearch = (queryString, cb) => {
    const results = queryString
        ? links.value.filter(createFilter(queryString))
        : links.value;
    // 调用回调函数返回建议对象
    cb(results);
};

const createFilter = (queryString) => {
    return (item) => {
        return item.title.toLowerCase().includes(queryString.toLowerCase());
    };
};

const loadAll = async () => {
    try {
        const response = await axios.get('http://localhost:80/index.php/index/getAllBaidubaikeData');
        // 假设后端返回的数据结构如下所示
        const data = response.data.data;
        return data.map((item) => ({
            id: item.id,
            title: item.title,
            intro: item.intro,
            url: item.url
        }));
    } catch (error) {
        console.error('Error fetching data:', error);
        return []; // 返回空数组或者其他默认值
    }
};

const handleSelect = (item) => {
    state.value = item.title;
    selectedId.value = item.id;
    console.log(item);
};

const handleIconClick = (ev) => {
    console.log(ev);
};

const handleButtonClick = () => {
    if (selectedId.value !== null) {
        find(selectedId.value);
    } else {
        console.log("No item selected");
    }
};

const find = (id) => {
    console.log("Selected item ID:", id);
    // 导航到 SearchResultPage 路由，并传递 id 参数
    router.push({ name: 'SearchResultPage', params: { "id": id } });
};

onMounted(async () => {
    links.value = await loadAll();
});
</script>
